package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.acticle.domain.Commodity;
import cn.wolfcode.luowowo.acticle.service.ICommodityService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/itemshop")
public class ItemShopController {

    @Reference
    private ICommodityService commodityService;

    @Reference
    private IUserInfoService userInfoService;

    /**
     * 道具商店首页
     *
     * @return
     */
    @RequestMapping("")
    @RequireLogin
    public String index(Model m, @UserParam UserInfo userInfo) {
        List<Commodity> list = commodityService.list();
        m.addAttribute("userInfo", userInfoService.get(userInfo.getId()));
        m.addAttribute("list", list);
        m.addAttribute("owenGood",commodityService.selectUserOwnedGoodsById(userInfo.getId()));
        m.addAttribute("size",commodityService.selectUserOwnedGoodsById(userInfo.getId()).size());
        return "itemshop/index";
    }

    /**
     * 道具介绍
     *
     * @return
     */
    @RequestMapping("/itemintroduc")
    public String itemintroduc() {

        return "itemshop/itemintroduc";
    }

    /**
     * 查询当前用户是否拥有某个商品
     *
     * @return
     */
    @RequestMapping("/owengood")
    @ResponseBody
    public AjaxResult owengood(Long id, @UserParam UserInfo userInfo) {
        int count = commodityService.selectUserIsOwenGood(id, userInfo.getId());
        if (count > 0) {
            return new AjaxResult();
        }
        return new AjaxResult("");
    }

    /**
     * 购买商品,维护关系
     * @param id
     * @param userInfo
     * @return
     */
    @RequestMapping("/addCommodity")
    @ResponseBody
    public AjaxResult addCommodity(Long id,int price, @UserParam UserInfo userInfo) {

        try {
            commodityService.insertRelation(userInfo.getId(),id);
            commodityService.updateNumber(id);
            userInfoService.updateIntegral(price,userInfo.getId());
            return new AjaxResult();
        } catch (Exception e) {
            return new AjaxResult(e.getMessage());
        }
    }

}
